<?php

use \GatewayWorker\Lib\Gateway;

class Tool
{
    public static $http_url="https://housedemo.dingcan.net.cn/";
    public static function create_uid_cache($uid,$type)
    {
        $str=$uid.$type;
        return md5($str);
    }

    public static function ObjectToArray($obj)
    {
        return (array)$obj;
        $res=array();

        foreach ($obj as $key=>$v){
            $res[$key]=$v;
        }
        return $res;
    }


    public static function error($msg)
    {
        $data=[
            'code'=>400,
            'type'=>'error',
            'msg'=>$msg
        ];
        return json_encode($data);
    }

    function curl_get($url, $token="",&$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
                'token:'.$token
            )
        );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

    function curl_post($url, array $params = array())
    {
        $data_string = json_encode($params);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
            )
        );
        $data = curl_exec($ch);
        curl_close($ch);
        return ($data);
    }

    public static function sendTogroup($type,$group,$data)
    {
        $res=[
            'code'=>200,
            'type'=>$type,
            'data'=>$data
        ];
        $res=json_encode($res);
        Gateway::sendToGroup($group,$res);
    }


    public static function success($type,$data,$client_id='')
    {
        $res=[
            'code'=>200,
            'type'=>$type,
            'data'=>$data
        ];
        $res=json_encode($res);

        if ($client_id){
            Gateway::sendToClient($client_id,$res);
        }else{
            Gateway::sendToAll($res);
        }

    }
}
